package com.sinodata.bsm.cicp.util.snmp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import net.percederberg.mibble.MibValueSymbol;

import org.apache.log4j.Logger;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.Variable;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.DefaultPDUFactory;
import org.snmp4j.util.TableEvent;
import org.snmp4j.util.TableUtils;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangpeng
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-8-26 上午10:23:36          wangpeng        1.0         To create
 * </p>
 * 
 * @since 
 * @see     
 */
public class GetData {
    private static Logger logger = Logger.getLogger(GetData.class);

    public static List<Object> getAllTableData(Class<Object> clas, CommunityTarget target) throws Exception {
        return null;
    }

    public static List<OMMappingInfo> getAllTableData(Snmp snmp, Class<? extends OMMappingInfo> clas, CommunityTarget target) throws Exception {
        OMMappingInfo mapping = clas.newInstance();
        String oid = mapping.getMappingOID();
        MibValueSymbol localMibValueSymbol = SnmpUtil.getMibSymbolByOid(oid);
        Vector<MibValueSymbol> mibNodeVector = SnmpUtil.getFieldsInMibNode(mapping, localMibValueSymbol);
        OID[] arrayOfOID = new OID[mibNodeVector.size()];
        for (int i = 0; i < mibNodeVector.size(); i++) {
            arrayOfOID[i] = new OID(mibNodeVector.get(i).getValue().toString());
        }
        TableUtils table = new TableUtils(snmp, new DefaultPDUFactory());
        List<TableEvent> tableEvents = table.getTable(target, arrayOfOID, null, null);
        List<TableEvent> rightTableEvents = new ArrayList<TableEvent>();
        for (int i = 0; i < tableEvents.size(); i++) {
            TableEvent event = tableEvents.get(i);
            if (event.isError())
                logger.error("[ERROR]\tTableEvent is error");
            if (event.getException() != null)
                logger.error("[ERROR]\tTableEvent get exception");
            if (event.getStatus() != 0)
                logger.error("[ERROR]\tTableEvent status != 0 ");
            if (event.getColumns() != null && event.getColumns().length >= 1) {
                rightTableEvents.add(event);
            }
        }
        List<OMMappingInfo> list = new ArrayList<OMMappingInfo>();
        for (int j = 0; j < rightTableEvents.size(); j++) {
            mapping = clas.newInstance();
            list.add(mapping);
            TableEvent localTableEvent = rightTableEvents.get(j);
            mapping.setTableIndexOID(localTableEvent.getIndex().toString());
            VariableBinding[] arrayOfVariableBinding = localTableEvent.getColumns();
            for (int k = 0; k < arrayOfVariableBinding.length; k++)
                try {
                    VariableBinding localVariableBinding = arrayOfVariableBinding[k];
                    if (localVariableBinding != null) {
                        String str2 = localVariableBinding.getOid().toString();
                        String str3 = localMibValueSymbol.getMib().getSymbolByOid(str2).getName();
                        Variable localVariable = localVariableBinding.getVariable();
                        SnmpUtil.setFieldValue(mapping, str3, localVariable);
                    }
                } catch (Exception e) {
                    logger.error("GetData", e);
                }
        }
        return list;
    }

    public static String snmpGet(String ip, String community, Integer port, int retries, long timeout, int version, String oid) throws Exception {
        Snmp snmp = null;
        try {
            snmp = new Snmp(new DefaultUdpTransportMapping());
            snmp.listen();

            CommunityTarget target = new CommunityTarget();
            target.setCommunity(new OctetString(community));
            target.setAddress(GenericAddress.parse("udp:" + ip.trim() + "/" + port));
            target.setRetries(retries);
            target.setTimeout(timeout);
            target.setVersion(version);

            PDU pdu = SnmpUtil.createGetPdu(oid);
            ResponseEvent responseEvent = snmp.send(pdu, target);
            PDU response = responseEvent.getResponse();
            if (response == null) {
                throw new IOException("snmp get " + ip + "下的" + oid + "超时");
            } else {
                if (response.getErrorStatus() == PDU.noError) {
                    Vector<? extends VariableBinding> vbs = response.getVariableBindings();
                    VariableBinding vb = vbs.get(0);
                    return vb.getVariable().toString();
                }
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (snmp != null) {
                try {
                    snmp.close();
                } catch (Exception e2) {
                }
            }
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        //        TransportMapping transport = new DefaultUdpTransportMapping();
        //        Snmp snmp = new Snmp(transport);
        //        snmp.listen();
        //
        //        CommunityTarget localCommunityTarget = new CommunityTarget();
        //        localCommunityTarget.setCommunity(new OctetString("public"));
        //
        //        Address localAddress = GenericAddress.parse("udp:172.168.0.7/161");
        //        localCommunityTarget.setAddress(localAddress);
        //        localCommunityTarget.setRetries(0);
        //        localCommunityTarget.setTimeout(5000);
        //        localCommunityTarget.setVersion(1);
        //
        //        List<OMMappingInfo> list = getAllTableData(snmp, MibInterfaceEntry.class, localCommunityTarget);
        //        for (OMMappingInfo e : list) {
        //            MibInterfaceEntry inter = (MibInterfaceEntry) e;
        //            if (inter.getIfIndex() == 4227626) {
        //                System.out.println("输出字节数:" + inter.getIfInOctets() + ";输入字节数：" + inter.getIfInOctets());
        //                break;
        //            }
        //        }
        //        String s = snmpGet("172.168.0.7", "public", 161, 0, 5000, 1, "1.3.6.1.2.1.1.3.0");
        //        System.out.println(s);
    }
}
